﻿namespace Atomic.Mvc.Validators
{
    using System.Collections.Generic;
    using System.Globalization;
    using Atomic.Extensions;

    /// <summary>
    /// 实体验证基类。
    /// </summary>
    /// <typeparam name="TEntity">实体类型。</typeparam>
    public abstract class EntityValidatorBase<TEntity> : IValidator<TEntity> where TEntity : class
    {
        /// <summary>
        /// 实体验证错误信息集合。
        /// </summary>
        private readonly IList<ValidatorError> _errors = new List<ValidatorError>();

        /// <summary>
        /// 验证实体。
        /// </summary>
        /// <param name="item">实体对象。</param>
        /// <returns>实体验证状态。</returns>
        public ValidatorState Validate(TEntity item)
        {
            ValidatorState state = new ValidatorState();

            this._errors.Clear();

            this.OnValidate(item);

            this._errors.ForEach(error => state.AddValidatorError(error));

            return state;
        }

        /// <summary>
        /// 验证实体。
        /// </summary>
        /// <param name="item">实体对象。</param>
        public abstract void OnValidate(TEntity item);

        /// <summary>
        /// 增加错误信息。
        /// </summary>
        /// <param name="key">错误信息唯一标识。</param>
        /// <param name="propertyName">验证失败的属性值的属性名，假如不是属性值，这里请设为 null。</param>
        /// <param name="errorMessage">错误信息。</param>
        /// <param name="args">格式化参数。</param>
        protected virtual void AddValidatorError(string key, string propertyName, string errorMessage, params object[] args)
        {
            _errors.Add(new ValidatorError { Key = key, PropertyName = propertyName, Message = string.Format(CultureInfo.InvariantCulture, errorMessage, args) });
        }
    }
}